/**
 * 系统后台数据库连接配置JS-systemDataSource.jsp
 */

// 项目路径
var strPath = window.document.location.pathname;
var postPath = "/gdp";

$(function () {


});
var app = new Vue({
    el: '#main-container',
    data: {
        loadingPage: true,
        appIdCatalogInfoListMap: {},
        servicetype: '',
        unAppIdList:[],
        checkedAllFlag: true,
        tableData: {
            total: 0,
            list: [],
        },
    },
    created: function () {
        this.initData();
    },
    mounted: function () {
    },

    watch: {
        // "tableData.list": function (n, o) {
        //     debugger
        //  
        // },


        'tableData.list': {
            handler(newName, oldName) {
                newName.forEach(i => {
                    if (i.dailyCount !== '无限制' && isNaN(Number(i.dailyCount))) {
                        i.dailyCount = 0;
                        showMsg("单日调用次数只能输入数字", 'error');
                    }
                })
            },
            immediate: true,
            deep: true // 开启深度监听，默认是false
        }
    },
    methods: {

        initData() {
            this.servicetype = this.getQueryString("servicetype");
            // 先获取所有的调用方
            let allAppList = this.getAllAppList();
            // 获选中 配置过精细化 的调用方
            let checkedAppList = this.getNewData();
            // 服务id
            let serviceId = this.getQueryString("id");

            allAppList.forEach(app => {
                // 从选中的调用方 筛选出数据 
                let filterAppList = checkedAppList.filter(cApp => cApp.appId === app.appId);
                if (filterAppList && filterAppList[0]) {
                    let checkedItem = filterAppList[0]
                    this.tableData.list.push(
                        {
                            status: true,
                            appServiceId: checkedItem.appServiceId,
                            appId: app.appId,
                            appCode: app.appCode,
                            appName: app.appName,
                            serviceId: checkedItem.serviceId,
                            startTime: checkedItem.startTime,
                            endTime: checkedItem.endTime,
                            startHour: "",
                            endHour: "",
                            dailyCount: checkedItem.dailyCount,
                            filterCatalogId: checkedItem.filterCatalogId,
                            filterStartTime: checkedItem.filterStartTime,
                            filterEndTime: checkedItem.filterEndTime
                        }
                    );
                } else {
                    // 只要是有一个未选中 就为false
                    this.checkedAllFlag = false;
                    this.tableData.list.push(
                        {
                            status: false,
                            appServiceId: '',
                            appId: app.appId,
                            appCode: app.appCode,
                            appName: app.appName,
                            serviceId: serviceId,
                            startTime: "",
                            endTime: "",
                            startHour: "",
                            endHour: "",
                            dailyCount: 0,
                            filterCatalogId: "",
                            filterStartTime: "",
                            filterEndTime: ""
                        }
                    );
                }
            })
            // 获取分组信息
            this.initCatalogList()
        },
        // 全选 取消全选
        clickTotalBox() {
            if (this.tableData.list) {
                this.tableData.list.forEach(item => item.status = !this.checkedAllFlag)
            }
        },

        clickAppRow(item) {
            // 当选中状态被点击的时候 证明是取消选中
            if (item.status) {
                this.unAppIdList.push(item.appId);
            } else {
                this.unAppIdList = this.unAppIdList.filter(i => i.appId !== item.appId);
            }
            
            item.status = !item.status;
            let n = this.tableData.list;
            if (n && n.length !== 0 && n.length === n.filter(i => i.status).length) {
                this.checkedAllFlag = true;
            } else {
                this.checkedAllFlag = false;
            }

         
        },
        /**
         * 获取所有的调用方
         * @returns {*[]}
         */
        getAllAppList() {
            let appList = [];
            // 这里目前预估数据量应该不大 前端暂时不做分页 分页参数写死 一旦数据量超过一万 必须要改成分页的
            $.ajax({
                url: postPath + '/accesscontrol/appcode/getDataPage?pageNo=1&pageSize=10000',
                type: "GET",
                async: false,
                success: function (res) {
                    if (res && res.success) {
                        appList = res.data.rows;
                    }
                }
            });
            return appList;
        },


        /**
         * 获取新的数据
         */
        getNewData: function () {
            let checkedAppList = [];
            var _this = this;
            $.ajax({
                url: postPath + '/accesscontrol/appserviceaccessconfig/getDataList',
                type: "POST",
                data: {serviceId: _this.getQueryString("id")},
                isShowLoader: true,
                dataType: "json",
                async: false,
                success: function (res) {
                    if (res && res.success) {
                        // _this.tableData.list = res.data;
                        checkedAppList = res.data;
                    }
                }
            });
            return checkedAppList;
        },


        /**
         * 查询分组信息
         * @param item
         */
        initCatalogList() {
            let appIdList = [];
            this.tableData.list.forEach(i => {
                appIdList.push(i.appId);
            })
            let _this = this;
            $.ajax({
                type: 'GET',
                url: postPath + '/accesscontrol/acAppCatalog/selectListByAppIds',
                data: {appIdList: appIdList},
                async: false,
                success: function (res) {
                    if (res.success) {
                        _this.appIdCatalogInfoListMap = res.data;
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });

        },
        //搜索
        doSearch: function () {
            this.getNewData();
        },
        goback: function () {
            window.location.href = postPath + "/prjService/index";
        },


        beforeSaveCommit(checkedList) {
            let stationParams = this.getInsertStationParams(checkedList);
            if (stationParams.length === 0) return true;
            return this.insertStation(stationParams);
        },

        insertStation(stationParams) {
            let flag = false;
            let serviceId = this.getQueryString("id");
            $.ajax({
                type: 'POST',
                url: postPath + '/accesscontrol/appserviceaccessconfig/insertStation?serviceId=' + serviceId,
                data: JSON.stringify(stationParams),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success) {
                        showMsg("操作成功!", "success");
                        flag = true;
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });
            return flag;
        },

        getInsertStationParams(checkedList) {
            let resParams = [];
            let _this = this;
            $.ajax({
                type: 'POST',
                url: postPath + '/accesscontrol/appserviceaccessconfig/getInsertStationParams',
                data: JSON.stringify(checkedList),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success) {
                        if (res.data && res.data.length && res.data.length > 0) {
                            resParams = res.data;
                        }
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });

            return resParams;
        },

        save: function () {
            let _this = this;
            let checkedList = _this.tableData.list.filter(i => i.status);
            if (checkedList){
                checkedList.forEach(c=>{
                    if(c.dailyCount === '无限制') c.dailyCount = 0;
                })
            }
            // 在提交保存分组信息之前 要在目标业务库中新增测站数据
            if (!this.beforeSaveCommit(checkedList)) return;
            $.ajax({
                type: 'POST',
                url: postPath + '/accesscontrol/appserviceaccessconfig/save',
                data: JSON.stringify({
                    serviceId: _this.getQueryString("id"),
                    unAppIdList: _this.unAppIdList,
                    acAppServiceRelation: checkedList,
                }),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success == true) {
                        if (res.data > 0) {
                            showMsg("操作成功!", "success");
                        }
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });
            document.location.reload();
        },
        startTimeComponent: function (index) {
            var _this = this;
            var attrName = "startTime";
            var _id = attrName + index;
            WdatePicker({
                el: _id,
                dateFmt: "yyyy-MM-dd HH:mm:ss",
                isShowClear: true,
                maxDate: "#F{$dp.$D(" + ('endTime' + index) + ")}",
                onpicked: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
                oncleared: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
            });
        },
        endTimeComponent: function (index) {
            var _this = this;
            var attrName = "endTime";
            var _id = attrName + index;
            WdatePicker({
                el: _id,
                dateFmt: "yyyy-MM-dd HH:mm:ss",
                isShowClear: true,
                minDate: "#F{$dp.$D(" + ('startTime' + index) + ")}",
                onpicked: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
                oncleared: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
            });
        },
        startHourComponent: function (index) {
            var _this = this;
            var attrName = "startHour";
            var _id = attrName + index;
            WdatePicker({
                el: _id,
                dateFmt: "HH:mm:ss",
                isShowClear: true,
                maxDate: "#F{$dp.$D(" + ('endHour' + index) + ")}",
                onpicked: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
                oncleared: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
            });
        },
        endHourComponent: function (index) {
            var _this = this;
            var attrName = "endHour";
            var _id = attrName + index;
            WdatePicker({
                el: _id,
                dateFmt: "HH:mm:ss",
                isShowClear: true,
                minDate: "#F{$dp.$D(" + ('startHour' + index) + ")}",
                onpicked: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
                oncleared: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
            });
        },
        //获取Query参数
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        },
        filterStartTimeComponent: function (index) {
            var _this = this;
            var attrName = "filterStartTime";
            var _id = attrName + index;
            WdatePicker({
                el: _id,
                dateFmt: "yyyy-MM-dd HH:mm:ss",
                isShowClear: true,
                maxDate: "#F{$dp.$D(" + ('filterEndTime' + index) + ")}",
                onpicked: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
                oncleared: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
            });
        },
        filterEndTimeComponent: function (index) {
            var _this = this;
            var attrName = "filterEndTime";
            var _id = attrName + index;
            WdatePicker({
                el: _id,
                dateFmt: "yyyy-MM-dd HH:mm:ss",
                isShowClear: true,
                minDate: "#F{$dp.$D(" + ('filterStartTime' + index) + ")}",
                onpicked: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
                oncleared: function () {
                    _this.tableData.list[index][attrName] = $("#" + _id).val();
                },
            });
        },
    }


})


function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}